package client

import (
	"chatting/model"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/data/validation"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/widget"
)

func (la *LocalApp) BuildRegister() fyne.Window {
	window := la.app.NewWindow("App")

	usernameEntry := widget.NewEntry()
	usernameEntry.Validator = validation.NewRegexp("^[a-zA-Z0-9_-]{3,16}$", "请输入3-16位字母和数字组成的用户名")
	passwordEntry := widget.NewEntry()
	passwordEntry.Password = true
	passwordEntry.Validator = validation.NewRegexp("[0-9A-Za-z]{6,16}$", "请输入6-16位可由字母或数字组成的密码")
	emailEntry := widget.NewEntry()
	emailEntry.Validator = validation.NewRegexp("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$", "请输入邮箱格式")

	form := widget.NewForm(
		widget.NewFormItem("用户名", usernameEntry),
		widget.NewFormItem("密码", passwordEntry),
		widget.NewFormItem("邮箱", emailEntry),
	)

	form.SubmitText = "提交"

	form.OnSubmit = func() {
		message := model.NewRegisterMessage(&model.User{
			Username: usernameEntry.Text,
			Password: passwordEntry.Text,
			Email:    emailEntry.Text,
		})
		la.client.sendChan <- message
		re := <-la.client.receiveChan

		plainMessage := re.(*model.ResPlainMessage)
		if !plainMessage.Status { //err
			dialog.ShowInformation("错误", plainMessage.Data.(string), window)
			return
		}
		dialog.ShowInformation("注册成功", "注册成功", window)
	}

	form.CancelText = "取消"
	form.OnCancel = func() {
		window.Close()
	}
	window.Resize(fyne.NewSize(300, 150))
	window.SetContent(form)
	return window

}
